//
//  KWTEditPlantGroupVC.m
//  RuiHeApp
//
//  Created by Yan Chen on 2024/10/15.
//

#import "KWTEditPlantGroupVC.h"
#import "NSString+YYUtil.h"
#import "KWTAddPlantGroupCell.h"
#import "UITableViewCell+Indicator.h"
#import "RHChoiceTimeZoneView.h"
#import "RHChoiceTypeView.h"

@interface KWTEditPlantGroupVC ()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic ,strong) UITableView *tableView;

@property (nonatomic ,strong) UIView *headerView;

@property (nonatomic ,strong) UIView *footerView;

@property (nonatomic ,strong) NSArray *titleArr;

@property (nonatomic ,strong) NSArray *placeholdArr;

@property (nonatomic ,strong) UITextView *textView;
@end

@implementation KWTEditPlantGroupVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = CFTabViewBgColor;
    self.navigationItem.title = @"编辑分组".rh_localized;
    [self setupUI];

}
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.textView.text = self.plantGroupModel.desc;
}

- (void)setupUI{
    self.titleArr = @[@"分组名称".rh_localized,@"分组类型".rh_localized,@"分组时区".rh_localized,@"分组区域".rh_localized];
    self.placeholdArr = @[@"请输入名称".rh_localized,@"请选择类型".rh_localized,@"--".rh_localized,@"请选择分组区域".rh_localized];
    
    
    _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
    [_tableView setBackgroundColor:UIColor.clearColor];
    [_tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    [_tableView setDelegate:self];
    [_tableView setDataSource:self];
    [_tableView registerClass:[KWTAddPlantGroupCell class] forCellReuseIdentifier:@"KWTAddPlantGroupCell"];
    [self.view addSubview:_tableView];
    _tableView.contentInset = UIEdgeInsetsMake(15, 0, 0, 0);
    _tableView.tableFooterView = self.footerView;
    
    
    QMUIButton *createBtn = [QMUIButton buttonWithType:UIButtonTypeCustom];
    [createBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [createBtn setTitle:@"确认".rh_localized forState:UIControlStateNormal];
    [createBtn.titleLabel setFont:[UIFont systemFontOfSize:16]];
    [createBtn.layer setCornerRadius:8];
    [createBtn setBackgroundColor:CMainColorGreen];
    [self.view addSubview:createBtn];
    [createBtn addTarget:self action:@selector(editPlantGroup) forControlEvents:UIControlEventTouchUpInside];
    [createBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_offset(15);
        make.right.mas_offset(-15);
        make.height.mas_equalTo(50);
        make.bottom.mas_offset(kSafe_bottom>0?-kSafe_bottom:-15);
    }];
    
    [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.right.mas_offset(0);
        make.bottom.equalTo(createBtn.mas_top).offset(-15);
    }];
}



- (UIView *)footerView{
    if(!_footerView){
        _footerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH,300)];
        [_footerView setBackgroundColor:UIColor.clearColor];
        _footerView.clipsToBounds = YES;
        
        UIView *view =  [[UIView alloc] initWithFrame:CGRectMake(15, 15, SCREEN_WIDTH-30,215)];
        [view setBackgroundColor:UIColor.whiteColor];
        [view rounded:8];
        [_footerView addSubview:view];
        
        
        QMUILabel *lab = [[QMUILabel alloc] init];
        [lab setText:@"分组描述".rh_localized];
        [lab setTextAlignment:NSTextAlignmentLeft];
        [lab setFont:[UIFont systemFontOfSize:14]];
        [lab setTextColor:kCOLOR_HEX(@"3F4443")];
        [view addSubview:lab];
        
        
        QMUITextView *textView = [[QMUITextView alloc]init];
        textView.font = kSYSTEMFONT(14);
        textView.layer.cornerRadius = 5;
        textView.layer.masksToBounds = YES;
        textView.backgroundColor = CFTabViewBgColor;
        textView.placeholder = @"请输入描述".rh_localized;
        textView.placeholderColor = kCOLOR_HEX_A(@"#171A1D", 0.3);
        textView.maximumTextLength = 100;
        textView.contentInset = UIEdgeInsetsMake(5, 5, 5, 5);
        [view addSubview:textView];
        self.textView = textView;
        
        QMUILabel *countLab = [QMUILabel labelWithFont:kSYSTEMFONT(14) textColor:kCOLOR_HEX_A(@"#171A1D", 0.3)];
        countLab.text = @"0/100";
        [view addSubview:countLab];
        
        
        
        [lab mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_offset(15);
            make.top.mas_offset(15);
            make.right.mas_offset(-15);
            make.height.mas_equalTo(20);
        }];
        
        [textView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_offset(15);
            make.right.mas_offset(-15);
            make.top.equalTo(lab.mas_bottom).offset(15);
            make.height.offset(150);
        }];
        
        [countLab mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.bottom.equalTo(textView).offset(-5);
        }];
        
        
        
        [[RACSignal merge:@[textView.rac_textSignal,RACObserve(textView, text)]]subscribeNext:^(NSString  *_Nullable text) {
            countLab.text = [NSString stringWithFormat:@"%ld/100",text.length];
        }];
      
    }
    return _footerView;
}

- (UIView *)headerView{
    if(!_headerView){
        _headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH,10)];
        [_headerView setBackgroundColor:UIColor.clearColor];
        
        UIView *view =  [[UIView alloc] initWithFrame:CGRectMake(15, 0, SCREEN_WIDTH-30,20)];
        [view setBackgroundColor:UIColor.whiteColor];
        [view round:8 RectCorners:UIRectCornerTopLeft|UIRectCornerTopRight];
        [_headerView addSubview:view];
        _headerView.clipsToBounds = YES;
    }
    return _headerView;
}

#pragma mark - UITableViewDelegate,UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return self.titleArr.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 10;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH,10)];
    [headerView setBackgroundColor:UIColor.clearColor];
        
    UIView *view =  [[UIView alloc] initWithFrame:CGRectMake(15, 0, SCREEN_WIDTH-30,20)];
    [view setBackgroundColor:UIColor.whiteColor];
    [view round:8 RectCorners:UIRectCornerTopLeft|UIRectCornerTopRight];
    [headerView addSubview:view];
    headerView.clipsToBounds = YES;
    
    return headerView;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    
    return 10;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
   
    UIView *footerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH,10)];
    [footerView setBackgroundColor:UIColor.clearColor];
        
    UIView *view =  [[UIView alloc] initWithFrame:CGRectMake(15, -10, SCREEN_WIDTH-30,20)];
    [view setBackgroundColor:UIColor.whiteColor];
    [view round:8 RectCorners:UIRectCornerBottomLeft|UIRectCornerBottomRight];
    [footerView addSubview:view];
    footerView.clipsToBounds = YES;
    
    return footerView;
   
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    KWTAddPlantGroupCell *cell = [tableView dequeueReusableCellWithIdentifier:@"KWTAddPlantGroupCell"];
    [cell.titleLab setText:self.titleArr[indexPath.row]];
   
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    NSArray *maxLengthArr = @[@"32",@"32",@"32",@"32"];
    NSArray *contentArr = @[ValidNullData(self.plantGroupModel.groupName),ValidNullData(self.plantGroupModel.type),ValidNullData(self.plantGroupModel.timezone),ValidNullData(self.plantGroupModel.region)];
    cell.textField.text = [contentArr safeObjectAtIndex:indexPath.row];
    [cell.textField setPlaceholder:self.placeholdArr[indexPath.row]];
    
    
    cell.textField.maximumTextLength = [maxLengthArr[indexPath.row] integerValue];
    if([self.titleArr[indexPath.row] isEqualToString:@"分组类型".rh_localized]){
        cell.textField.userInteractionEnabled = NO;
        cell.textField.textColor = kCOLOR_HEX_A(@"#171A1D", 0.3);
    }else{
        
        cell.textField.userInteractionEnabled = YES;
        cell.textField.textColor = kCOLOR_HEX(@"3F4443");
    }
    
    kWeakSelf;
    [cell hideLine:(indexPath.row == self.titleArr.count - 1)];
  
    cell.arrowImg.hidden = ([self.titleArr[indexPath.row] isEqualToString:@"分组名称".rh_localized]);
    __weak __typeof(cell) weakCell = cell;
    cell.clickBlock = ^{
        if([weakSelf.titleArr[indexPath.row] isEqualToString:@"分组类型".rh_localized]){
            [weakSelf.view endEditing:YES];
//            [weakSelf getPlantType];
        }else if([weakSelf.titleArr[indexPath.row] isEqualToString:@"分组时区".rh_localized]){
            [weakSelf.view endEditing:YES];
            [weakSelf showTimeZoneList];
        }else if([weakSelf.titleArr[indexPath.row] isEqualToString:@"分组区域".rh_localized]){
            [weakSelf.view endEditing:YES];
            [weakSelf showRegionList];
        }
        else{
            [weakCell.textField becomeFirstResponder];
         
        }
        
        
    };
    return cell;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
   
    
}


#pragma mark -------  编辑电站分组--------------
-(void)editPlantGroup
{
    NSString *plantName = [self getTextFromCellIndex:0];
    NSString *plantType = [self getTextFromCellIndex:1];
    NSString *des = self.textView.text;
    if (plantName.length == 0) {
        [QMUITips showInfo:@"请输入分组名称".rh_localized];
        return;
    }
    if (plantType.length == 0) {
        [QMUITips showInfo:@"请输入分组类型".rh_localized];
        return;
    }
    if (des.length == 0) {
        [QMUITips showInfo:@"请输入分组描述".rh_localized];
        return;
    }
    if (self.plantGroupModel.timezone.length == 0) {
        [QMUITips showInfo:@"请选择分组时区".rh_localized];
        return;
    }
    if (self.plantGroupModel.timezone.length == 0) {
        [QMUITips showInfo:@"请选择分组区域".rh_localized];
        return;
    }
    kWeakSelf;
    [QMUITips showLoading:@"".rh_localized inView:self.view];
    NSDictionary *para = @{@"groupName":plantName,
                           @"description":des,
                           @"timezone":self.plantGroupModel.timezone,
                           @"region":self.plantGroupModel.region,
                           @"id":@(self.plantGroupModel.groupId)
                         };
   
    
    [BaseModel startPutWithCompletionAPIKey:H_editPlantGroup argument:para requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        if(resultModel.code == 200){
            [QMUITips showSucceed:@"成功".rh_localized];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                if (self.editBlock) {
                    self.editBlock();
                }
                [weakSelf.navigationController popViewControllerAnimated:YES];
            });
            
        }
        } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
            
        }];
}


#pragma mark ------ 选择时区 -------
-(void)showTimeZoneList
{
    
    RHChoiceTimeZoneView *choiceView = [[RHChoiceTimeZoneView alloc] init];
    choiceView.curTimeZone = self.plantGroupModel.timezone;
    [choiceView scorllToCurrentValue];
    [choiceView showAnimation];
    kWeakSelf;
    choiceView.choiceResultBlock = ^(NSString * _Nonnull zone) {
        if (zone == nil) {
            return;
        }
        weakSelf.plantGroupModel.timezone = zone;
        [weakSelf.tableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:2 inSection:0]] withRowAnimation:UITableViewRowAnimationNone];
    };
}

#pragma mark ------ 选择区域 -------
-(void)showRegionList
{
    [QMUITips showLoadingInView:self.view];
    [BaseModel startGetWithCompletionAPIKey:H_getGroupRegion argument:@{} requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        if (resultModel.code == 200) {
            NSArray *arr = request.responseJSONObject[@"data"];
            NSMutableArray *arrM = [NSMutableArray array];
            [arr enumerateObjectsUsingBlock:^(NSDictionary*  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                [arrM addObject:ValidNullDataToString(obj[@"region"], @"")];
            }];
            RHChoiceTypeView *choiceView = [[RHChoiceTypeView alloc] init];
            choiceView.typeList = arrM.copy;
            choiceView.curType = self.self.plantGroupModel.region;
            [choiceView scorllToCurrentValue];
            [choiceView showAnimation];
            kWeakSelf;
            choiceView.choiceResultBlock = ^(NSString * _Nonnull zone) {
                if (zone == nil) {
                    return;
                }
                weakSelf.plantGroupModel.region = zone;
                [weakSelf.tableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:3 inSection:0]] withRowAnimation:UITableViewRowAnimationNone];
            };
        }
    } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        
    }];
    
    
}

-(NSString*)getTextFromCellIndex:(NSInteger)index
{
    KWTAddPlantGroupCell *cell = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:index inSection:0]];
    return cell.textField.text;
   
}


@end
